package com.vframework.exception;

import com.vframework.common.response.R;
import com.vframework.common.response.enums.ReturnEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLException;

@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(BaseException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleBaseException(BaseException ex) {
        logger.error(ex.getMessage(), ex);
        return R.fail(ex.getResultEnum());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleRuntimeException(RuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        return R.fail(ex);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleMethodArgumentNotValidException(RuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        return R.fail(ReturnEnum.PARAMS_INVALID);
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class, MissingServletRequestParameterException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleHttpRequestMethodNotSupportedException(RuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        return R.fail(ReturnEnum.METHOD_INVALID);
    }

    @ExceptionHandler({SQLException.class, DataAccessException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleSQLException(RuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        return R.fail(ReturnEnum.DATA_ACCESS_ERROR);
    }
}
